import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/views/login'
import Layout from '@/views/layout'
import NotFound from '@/views/404'
import Home from '@/views/layout/Home'
import QA from '@/views/layout/QA'
import User from '@/views/layout/User'
import Video from '@/views/layout/Video'
import UserEdit from '@/views/layout/User/edit'
import Search from '@/views/search'
import SearchResult from '@/views/search/result'
import Article from '@/views/article'
import Chat from '@/views/layout/User/chat'
import store from '@/store'

// 解决路由报错问题
// https://github.com/vuejs/vue-router/issues/2881#issuecomment-520554378
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}
Vue.use(VueRouter)

const routes = [
  {
    path: '/user/edit',
    component: UserEdit
  },
  {
    path: '/user/chat',
    component: Chat
  },
  {
    path: '/',
    component: Layout,
    children: [
      {
        path: '',
        component: Home,
        meta: {
          isKeepAlive: true
        }
      },
      {
        path: 'user',
        component: User
      },
      {
        path: 'qa',
        component: QA
      },
      {
        path: 'video',
        component: Video
      }
    ]
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/search',
    component: Search
  },
  {
    path: '/search/result',
    component: SearchResult
  },
  {
    path: '/article/:id',
    component: Article
  },
  {
    path: '*',
    component: NotFound
  }
]

const router = new VueRouter({
  routes
})

// 前置导航守卫 to:到哪去  from:从哪来  next():next代表放行
// 1. 判断是否有token
// 2. 如果有，直接放行
// 3. 如果没有，判断去的页面是否需要登录
// 4. 如果需要，跳转到登录页面
// 5. 如果不需要，放行
const loginUrls = ['/user', '/user/edit', '/chat']
router.beforeEach((to, from, next) => {
  const token = store.state.user.token.token
  // 有token
  if (token) {
    return next()
  }
  // 没有token
  if (loginUrls.includes(to.path)) {
    router.push({
      path: '/login',
      query: {
        back: to.path
      }
    })
  } else {
    next()
  }
})

export default router
